import java.util.Scanner;

public class Page {
    public static int[] blockNumber;
    public static int phyaddress;
    public static int[] preparedNumber={0,42,29,15,45,31,44,43,41,28,
                                        1,30,12,24,6,32,14,27,13,46,
                                        7,33,10,22,40,2,51,11,39,23,
                                        49,50,26,16,25,4,47,17,3,48,
                                        52,36,58,35,57,34,21,63,5,37,
                                        18,8,62,56,20,54,60,19,38,9};
    public static void menu(){
        int r,flg ;

        System.out.println("欢迎来到页式地址重定位模拟系统"+ '\n'
                + "1.显示整张页表信息" + '\n'
                + "2.计算物理地址" + '\n'
                + "3.退出程序");
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入页项长度：");
        int pageLength=scanner.nextInt();
        System.out.println("请输入页表大小：");
        int pageAll=scanner.nextInt();
        System.out.println("页表生成中...");
        blockNumber=new int[pageAll];
        for (int i = 0; i < pageAll; i++) {
            blockNumber[i]=preparedNumber[i];
        }
        System.out.print("页表生成完毕...\n");
        while(true){
            System.out.println("请选择功能：");
            flg = scanner.nextInt();
            if (flg == 1) {
                showPageTable(pageAll, blockNumber);
            } else if (flg == 2) {
                int result=calPhyAdd(pageAll, pageLength);
                if(result==-1){
                    System.out.println("越界访问，请重新进行选择！！！");
                }else{
                    System.out.println("物理地址为：" + phyaddress);
                }
            } else if (flg == 3) {
                System.out.println("程序结束....");
                return;
            }else{
                System.out.println("请选择符合规定的功能");
            }
        }
    }
    public static void showPageTable(int pageAll,int[] blockNumber){
        System.out.println("页号"+"   "+"块号");
        for (int i = 0; i < pageAll; i++) {
            System.out.println(i+"  --> "+blockNumber[i]);
        }
    }
    public static int calPhyAdd(int pageAll,int pageLength){
        Scanner scanner=new Scanner(System.in);
        int AD;
        System.out.println("请输入逻辑地址:");
        int logicalNumber=scanner.nextInt();
        //检查逻辑地址&计算物理地址
        if(checkAdd(logicalNumber,pageAll,pageLength)){
            AD=(int)(logicalNumber/pageAll);
            int shift=logicalNumber%pageAll;
            phyaddress=blockNumber[AD]*pageLength+shift;
            return phyaddress;
        }else {
            return -1;
        }

    }
    //检查逻辑地址是否越界
    public static boolean checkAdd(int logicalNumber,int pageAll,int pageLength){
        if(logicalNumber>pageAll*pageLength){
            return false;
        }return true;
    }


    public static void main(String[] args) {
        menu();
    }
}